package com.ruoyi.system.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.system.domain.BaseContest;
import com.ruoyi.system.domain.BaseTournament;
import com.ruoyi.system.mapper.BaseTournamentMapper;
import com.ruoyi.system.service.IBaseContestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Wangbj
 * @date 2024年04月22日 21:16
 */
@Component
@Slf4j
public class BaseTournamentStateJob {

    @Resource
    BaseTournamentMapper baseMapper;

    @Resource
    private IBaseContestService iBaseContestService;
    @Resource
    private RedisService redisService;
//    @Scheduled(cron = "0 0/1 * * * ?")
//    private void task() {
//        //拿到所有时间到了，状态还是未开始的数据
//        List<BaseTournament> list = baseMapper.getListByTime();
//        log.info("比赛状态修正定时器开始执行，修正【{}】个",list.size());
//        //后续可能会推送当前比赛开始了等等。。。
//
//
//        if (CollectionUtil.isNotEmpty(list)) {
//            list.forEach(item -> {
//                LambdaUpdateWrapper<BaseTournament> updateWrapper = new LambdaUpdateWrapper<>();
//                updateWrapper.eq(BaseTournament::getId, item.getId());
//                updateWrapper.set(BaseTournament::getState, 1);
//                updateWrapper.set(BaseTournament::getUpdateTime, DateUtil.date());
//                baseMapper.update(null, updateWrapper);
//            });
//        }
//        log.info("比赛状态修正定时器结束..");
//    }

    @Scheduled(cron = "0 0 1 * * ?")
    private void task() {
        LambdaQueryWrapper<BaseContest> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseContest::getIsDeleted,0);
        List<BaseContest> list = iBaseContestService.list(wrapper);
        if (CollUtil.isEmpty(list)){
            return;
        }
        log.info("定时同步联赛点赞数量开始,总{}个",list.size());
        list.forEach(bo ->{
            Integer cacheObject = Convert.toInt(redisService.getCacheObject(Constants.GOOD_NUM + bo.getId()),0);
            if (bo.getGoodNum() < cacheObject){
                bo.setGoodNum(cacheObject);
            }
        });
        iBaseContestService.updateBatchById(list);
    }
}
